const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const moment = require('moment')

exports.main = async event => {
  try {
    const { OPENID } = cloud.getWXContext()
    let date = moment().format('YYYY-MM-DD')

    // 防止重复存储
    let user = await db
      .collection('user')
      .where({
        id: event.id,
        openid: OPENID,
      })
      .get()

    let result = {}
    if (user.data.length == 0) {
      // 存储用户信息
      result = await db.collection('user').add({
        data: {
          openid: OPENID,
          days: 0,
          date: date,
        },
      })
    }

    return result
  } catch (err) {
    console.log(err)
    return err
  }
}
